import { Linking } from 'react-native';

const TEL = 'tel:';
const SMS = 'sms:';
function openURL(url, callback, errCallback) {
  Linking.canOpenURL(url)
    .then(supported => {
      if (supported) {
        return Linking.openURL(url)
          .then(() => {
            callback && callback();
          })
          .catch(err => {
            errCallback && errCallback(err);
          });
      }

      errCallback && errCallback(new Error("Can't handle url: " + url));
    })
    .catch(err => {
      errCallback && errCallback(err);
    });
}

// 拨打电话或者发送短信的锁
let linkingLock = false;

// 拨打电话
export function makeACall(phoneNumber, errCallback) {
  if (linkingLock) {
    return;
  }

  linkingLock = true;
  openURL(
    TEL + phoneNumber,
    () => {
      linkingLock = false;
    },
    err => {
      linkingLock = false;
      // 2019.6.11 因为区分不了是点击取消按钮还是其它错误，经过和麦楚焜讨论，暂时不处理错误
      // errCallback && errCallback(err.message);
    }
  );
}

// 发送短信
export function sendMessage(phoneNumber, errCallback) {
  if (linkingLock) {
    return;
  }

  linkingLock = true;
  openURL(
    SMS + phoneNumber,
    () => {
      linkingLock = false;
    },
    err => {
      linkingLock = false;
      // 2019.6.11 因为区分不了是点击取消按钮还是其它错误，经过和麦楚焜讨论，暂时不处理错误
      // errCallback && errCallback(err.message);
    }
  );
}
